package com.majie.protocolResolver;

import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.ProtocolResolver;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;

import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Logger;

/**
 * 自定义协议
 */
public class MyProtocolResolver implements ProtocolResolver {
	private static final Logger logger = Logger.getLogger(MyProtocolResolver.class.getName());

	@Override
	public Resource resolve(String location, ResourceLoader resourceLoader) {
		if (location.startsWith("my")) {
			logger.info("MyProtocolResolver resolve this resource....");
			return resourceLoader.getResource(location.replace("my", "classpath"));
		}
		return null;
	}

	public static void main(String[] args) throws IOException {
		DefaultResourceLoader bf = new DefaultResourceLoader();
		// 添加自定义的资源协议解析器
		bf.addProtocolResolver(new MyProtocolResolver());

		Resource resource = bf.getResource("my:a.txt");

		InputStream inputStream = resource.getInputStream();

		byte[] bytes = new byte[1024];
		inputStream.read(bytes);

		logger.info(new String(bytes));
	}
}